using Microsoft.Extensions.Logging;
using System.Runtime.CompilerServices;

namespace hao_Common.Logging.Helpers
{
    /// <summary>
    /// 日志帮助类
    /// </summary>
    public static class LogHelper
    {
        /// <summary>
        /// 记录业务操作日志
        /// </summary>
        public static void LogBusinessOperation(this ILogger logger, string operation, object? data = null, 
            [CallerMemberName] string? memberName = null, [CallerFilePath] string? filePath = null)
        {
            var context = new
            {
                Operation = operation,
                Data = data,
                Method = memberName,
                SourceFile = Path.GetFileName(filePath),
                Timestamp = DateTime.UtcNow
            };

            logger.LogInformation("业务操作: {Operation} {@Context}", operation, context);
        }

        /// <summary>
        /// 记录数据库操作日志
        /// </summary>
        public static void LogDatabaseOperation(this ILogger logger, string operation, string? tableName = null, 
            object? parameters = null, long? elapsedMs = null)
        {
            var context = new
            {
                Operation = operation,
                TableName = tableName,
                Parameters = parameters,
                ElapsedMilliseconds = elapsedMs,
                Timestamp = DateTime.UtcNow
            };

            logger.LogDebug("数据库操作: {Operation} {@Context}", operation, context);
        }

        /// <summary>
        /// 记录外部服务调用日志
        /// </summary>
        public static void LogExternalServiceCall(this ILogger logger, string serviceName, string endpoint, 
            string method, int? statusCode = null, long? elapsedMs = null, object? requestData = null)
        {
            var context = new
            {
                ServiceName = serviceName,
                Endpoint = endpoint,
                Method = method,
                StatusCode = statusCode,
                ElapsedMilliseconds = elapsedMs,
                RequestData = requestData,
                Timestamp = DateTime.UtcNow
            };

            var logLevel = statusCode >= 400 ? LogLevel.Warning : LogLevel.Information;
            logger.Log(logLevel, "外部服务调用: {ServiceName} {Method} {Endpoint} {@Context}", 
                serviceName, method, endpoint, context);
        }

        /// <summary>
        /// 记录用户操作日志
        /// </summary>
        public static void LogUserAction(this ILogger logger, string userId, string action, 
            object? details = null, string? ipAddress = null)
        {
            var context = new
            {
                UserId = userId,
                Action = action,
                Details = details,
                IpAddress = ipAddress,
                Timestamp = DateTime.UtcNow
            };

            logger.LogInformation("用户操作: {UserId} {Action} {@Context}", userId, action, context);
        }

        /// <summary>
        /// 记录性能日志
        /// </summary>
        public static void LogPerformance(this ILogger logger, string operation, long elapsedMs, 
            object? additionalData = null)
        {
            var context = new
            {
                Operation = operation,
                ElapsedMilliseconds = elapsedMs,
                AdditionalData = additionalData,
                Timestamp = DateTime.UtcNow
            };

            var logLevel = elapsedMs > 5000 ? LogLevel.Warning : LogLevel.Information;
            logger.Log(logLevel, "性能监控: {Operation} 耗时 {ElapsedMs}ms {@Context}", 
                operation, elapsedMs, context);
        }

        /// <summary>
        /// 记录安全相关日志
        /// </summary>
        public static void LogSecurity(this ILogger logger, string eventType, string? userId = null, 
            string? ipAddress = null, object? details = null)
        {
            var context = new
            {
                EventType = eventType,
                UserId = userId,
                IpAddress = ipAddress,
                Details = details,
                Timestamp = DateTime.UtcNow
            };

            logger.LogWarning("安全事件: {EventType} {@Context}", eventType, context);
        }

        /// <summary>
        /// 记录错误日志（带上下文）
        /// </summary>
        public static void LogErrorWithContext(this ILogger logger, Exception exception, string operation, 
            object? context = null)
        {
            var errorContext = new
            {
                Operation = operation,
                Context = context,
                ExceptionType = exception.GetType().Name,
                Message = exception.Message,
                StackTrace = exception.StackTrace,
                Timestamp = DateTime.UtcNow
            };

            logger.LogError(exception, "操作异常: {Operation} {@ErrorContext}", operation, errorContext);
        }

        /// <summary>
        /// 记录微服务间调用日志
        /// </summary>
        public static void LogMicroserviceCall(this ILogger logger, string fromService, string toService, 
            string operation, bool success, long? elapsedMs = null, object? data = null)
        {
            var context = new
            {
                FromService = fromService,
                ToService = toService,
                Operation = operation,
                Success = success,
                ElapsedMilliseconds = elapsedMs,
                Data = data,
                Timestamp = DateTime.UtcNow
            };

            var logLevel = success ? LogLevel.Information : LogLevel.Warning;
            logger.Log(logLevel, "微服务调用: {FromService} -> {ToService} {Operation} {@Context}", 
                fromService, toService, operation, context);
        }
    }
}